<template>
  <div class="table-box">
    <ProTable ref="proTable" title="产品列表" :columns="columns" :data="PCFrequestList">
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <template #operation="scope">
        <el-button type="primary" link :icon="Check" @click="showDialog(scope.row)">接受</el-button>
        <el-button type="primary" link :icon="Close" @click="deleteRequest(scope.row)">拒绝</el-button>
      </template>
    </ProTable>
    <DialogComponent ref="PCFinputRef" @submit="handleSubmit" />
    <ProductDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="ts" name="useProTable">
import { ref, onMounted } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import { ProTableInstance } from "@/components/ProTable/interface";
import { Close, Check } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import axios from "axios";
const baseUrl = import.meta.env.VITE_BASE_URL;
import ProductDrawer from "@/views/proTable/components/ProductDrawer.vue";
import DialogComponent from "./components/DialogComponent.vue"; // 根据你的目录结构调整
const PCFinputRef = ref<InstanceType<typeof DialogComponent> | null>(null);
const proTable = ref<ProTableInstance>();
const PCFrequestList = ref();

onMounted(() => {
  initFormData();
});

const initFormData = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
    const userId = Number(userInfo.id) || 0; // 如果没有 id，则使用默认值 0
    //数据库
    const response = await axios.get(baseUrl + "/api/carbon/getPCFrequestsByUserId?userId=" + userId);
    console.log("响应数据_外购产品请求列表:", response.data);
    if (response.data && response.data.code === 200) {
      PCFrequestList.value = response.data.data;
      console.log("请求列表:", PCFrequestList.value);
    } else {
      // 处理后端返回的错误信息
      const errorMsg = response.data.msg || "获取请求列表失败";
      console.error("获取请求列表错误:", errorMsg);
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error("获取请求列表出错:", error);
    ElMessage.error("获取请求列表失败，可能是因为参数错误或网络问题");
  }
};

/**显示弹窗 */
const showDialog = (row: any) => {
  if (PCFinputRef.value) {
    PCFinputRef.value.openDialog(row);
  } else {
    console.error("dialogRef.value 为空，组件可能未挂载");
  }
};

// 表格配置项
const columns = [
  { prop: "productName", label: "申请产品名称" },
  { prop: "description", label: "申请产品描述" },
  { prop: "startFactoryName", label: "申请单位" },
  { prop: "contactEmail", label: "负责人邮箱" },
  { prop: "contactPhone", label: "负责人联系电话" },
  { prop: "operation", label: "操作", fixed: "right", width: 200 } // 操作列
];

async function handleSubmit(data: number, row: any) {
  try {
    const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
    const userId = Number(userInfo.id) || 0; // 如果没有 id，则使用默认值 0
    console.log("data 类型:", typeof data, "，值为:", data);
    const response = await axios.post(
      baseUrl + "/api/carbon/acceptPCFrequest?projectId=" + row.projectId + "&productId=" + row.productId,
      {
        pcfValue: data,
        userId: userId
      }
    );
    if (response.data && response.data.code !== 200) {
      // 后端返回错误
      console.error("后端错误：", response.data.msg || response.data.message || "未知错误");
    } else {
      // 正常处理
      PCFrequestList.value = PCFrequestList.value.filter(
        (item: any) => !(item.projectId === row.projectId && item.productId === row.productId)
      );
      ElMessage({
        type: "success",
        message: "提交成功!"
      });
      console.log("提交成功:", response.data);
    }
  } catch (error) {
    console.error("提交失败:", error);
  }
}

//拒绝
const deleteRequest = (row: any) => {
  ElMessageBox.confirm("是否拒绝请求?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  }).then(async () => {
    try {
      const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
      const userId = Number(userInfo.id) || 0; // 如果没有 id，则使用默认值 0
      const response = await axios.post(
        baseUrl + "/api/carbon/rejectPCFrequest?projectId=" + row.projectId + "&productId=" + row.productId,
        {
          userId: userId
        }
      );
      if (response.data && response.data.code === 200) {
        PCFrequestList.value = PCFrequestList.value.filter(
          (item: any) => !(item.projectId === row.projectId && item.productId === row.productId)
        );
      } else {
        const errorMsg = response.data.msg || "拒绝失败";
        console.error("拒绝错误:", errorMsg);
        ElMessage.error(errorMsg);
      }
      ElMessage({
        type: "success",
        message: "操作成功!"
      });
    } catch (error) {
      console.error("提交失败:", error);
    }
  });
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof ProductDrawer> | null>(null);
</script>
<style scoped>
/* 隐藏数字输入框右侧的调整按钮 */
.el-input[type="number"]::-webkit-outer-spin-button,
.el-input[type="number"]::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
.el-input[type="number"] {
  appearance: textfield;
  -moz-appearance: textfield;
}
</style>
